package leetcode.d_100_199;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class P139 {
    public static void main(String[] args) {
        P139 test = new P139();
        List<String> wordDict = Arrays.asList("leet", "code");
        String s = "leetcode";
        System.out.println(test.wordBreak(s, wordDict)); // true
    }

    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<>();
        for (int i=0; i<wordDict.size(); i++) {
            set.add(wordDict.get(i));
        }
        int n = s.length();
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;
        for(int j=1; j<n+1; j++) {
            for (int i=0; i<=j; i++) {
                if (dp[i] && set.contains(s.substring(i, j))) {
                    dp[j] = true;
                    break;
                }
            }
        }
        return dp[n];
    }
}
